import React, { } from "react";
import { GroupProps, useFrame, useLoader } from "@react-three/fiber";
import { Mesh, Object3D, Scene } from "three";
import { vec3 } from "@react-three/rapier";
import { DragablePart } from "./DragablePart";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";



export function Assemble(props: GroupProps & { src: string, firstPartName: string, onAssembled: ((set: boolean) => void), onDragging: ((set: boolean) => void) }) {
    const gltf = useLoader(GLTFLoader,props.src)
    const meshes: any[] = gltf.scene.children
    const trueParts: any = []
    meshes.map((e) => trueParts.push({
        name: e.name,
        true: false
    }))

    let flag: boolean
    let completed = false
    useFrame(() => {
        if (!completed) {
            flag = true
            trueParts.forEach((e: any) => {
                if (e.true == false) {
                    flag = false
                }
            })
            if (flag) {
                props.onAssembled(flag)
                completed = true
            }
        }
    }
    )
    let i = 0


    return (
        <group {...props}>
            {meshes.map((element) => {
                i++
                return (
                    <DragablePart
                        onDragging={props.onDragging}
                        key={element.name}
                        startPosition={
                            element.name == props.firstPartName ? element.position : vec3({
                                x: 10 * Math.cos(i * (2 * Math.PI / (meshes.length - 1))),
                                y: element.position.y, z: 10 * Math.sin(i * (2 * Math.PI / (meshes.length - 1)))
                            })
                        }
                        geometry={element.geometry}
                        material={element.material}
                        truePosition={element.position}
                        name={element.name}
                        true={trueParts[i - 1]}
                    />
                )
            })}
        </group>
    );
}


